package com.yjj.teaching_platform.common.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.yjj.teaching_platform.config.KaptchaConfig;
import com.yjj.teaching_platform.utils.BeanUtil;
import org.apache.catalina.core.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Author: YJJ
 * Description:
 */
@Controller
public class VerificationController {

    @RequestMapping("/getVerificationCode")
    public void getVerificationCode(HttpServletRequest request, HttpServletResponse response) {

        /**
         * 验证码正确值在session里
         */
        byte[] out = null;
        ByteArrayOutputStream jpgOutputStream = new ByteArrayOutputStream();
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(KaptchaConfig.class);
        DefaultKaptcha defaultKaptcha = context.getBean(DefaultKaptcha.class);
        try{
            String createText = defaultKaptcha.createText();
            request.getSession().setAttribute("verify_session_code",createText);
            BufferedImage bufferedImage = defaultKaptcha.createImage(createText);
            ImageIO.write(bufferedImage,"jpg",jpgOutputStream);
            out = jpgOutputStream.toByteArray();
            response.setHeader("Cache-Control", "no-store");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpeg");
            ServletOutputStream responseOutputStream = response.getOutputStream();
            responseOutputStream.write(out);
            responseOutputStream.flush();
            responseOutputStream.close();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}
